import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, Select, Space, Tag, Modal, message, Descriptions, Popconfirm, DatePicker, Row, Col, Statistic } from 'antd';
import { SearchOutlined, ReloadOutlined, EyeOutlined, CheckOutlined, CloseOutlined, ShoppingCartOutlined, ClockCircleOutlined, CalendarOutlined, PlusOutlined, SwapOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { Option } = Select;
const { RangePicker } = DatePicker;

// 获取订单列表
const fetchOrders = async (params) => {
    return request('/api/v1/order', {
        method: 'GET',
        params,
    });
};

// 获取订单详情
const fetchOrderDetail = async (id) => {
    return request(`/api/v1/order/${id}`, {
        method: 'GET',
    });
};

// 更新订单状态
const updateOrderStatus = async (data) => {
    return request('/api/v1/order/status', {
        method: 'POST',
        data,
    });
};

// 获取门店列表
const fetchStores = async () => {
    return request('/api/v1/store', {
        method: 'GET',
        params: { pageSize: 100, status: 1 },
    });
};

// 获取会员列表
const fetchMembers = async () => {
    return request('/api/v1/member/batch', {
        method: 'POST',
        data: { ids: [] },
    });
};

// 获取场地列表
const fetchVenues = async (storeId) => {
    return request('/api/v1/venue', {
        method: 'GET',
        params: { pageSize: 100, store_id: storeId },
    });
};

// 订单状态映射
const orderStatusMap = {
    0: { text: '已支付', color: 'gold' },
    1: { text: '待确认', color: 'gold' },
    2: { text: '已确认', color: 'blue' },
    3: { text: '已完成', color: 'green' },
    4: { text: '已取消', color: 'red' },
    5: { text: '已改签', color: 'orange' },
};

// 支付状态映射
const paymentStatusMap = {
    1: { text: '未支付', color: 'default' },
    2: { text: '已支付', color: 'green' },
    3: { text: '已退款', color: 'orange' },
};

const OrderList = () => {
    const [createOrderVisible, setCreateOrderVisible] = useState(false);
    const [createOrderForm] = Form.useForm();
    const [orders, setOrders] = useState([]);
    const [stores, setStores] = useState([]);
    const [venues, setVenues] = useState([]);
    const [members, setMembers] = useState([]);
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();
    const [statusForm] = Form.useForm();
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const [searchParams, setSearchParams] = useState({});
    const [detailVisible, setDetailVisible] = useState(false);
    const [statusVisible, setStatusVisible] = useState(false);
    const [currentOrder, setCurrentOrder] = useState(null);
    const [rescheduleVisible, setRescheduleVisible] = useState(false);
    const [rescheduleForm] = Form.useForm();
    const [targetStatus, setTargetStatus] = useState('');
    const [statistics, setStatistics] = useState({
        total_orders: 0,
        pending_orders: 0,
        today_orders: 0,
        total_amount: 0,
    });

    // 获取订单列表
    const fetchOrderList = async () => {
        try {
            setLoading(true);
            const res = await fetchOrders({
                page: pagination.current,
                pageSize: pagination.pageSize,
                ...searchParams,
            });
            if (res.success) {
                const orderList = res.data.list || [];
                setOrders(orderList);
                setPagination({
                    ...pagination,
                    total: res.data.total,
                });
                // 设置统计数据
                if (res.data.statistics) {
                    setStatistics(res.data.statistics);
                }
                
                // 获取相关联的场地、会员信息
                await fetchRelatedData(orderList);
            } else {
                message.error(res.message || '获取订单列表失败');
            }
        } catch (error) {
            console.error('获取订单列表出错:', error);
            message.error('获取订单列表失败');
        } finally {
            setLoading(false);
        }
    };
    
    // 获取关联数据
    const fetchRelatedData = async (orderList) => {
        try {
            // 提取会员ID、场地ID
            const memberIds = Array.from(new Set(orderList.map(order => order.member_id).filter(Boolean)));
            const venueIds = Array.from(new Set(orderList.map(order => order.venue_id).filter(Boolean)));
            
            // 如果有会员ID，获取会员信息
            if (memberIds.length > 0) {
                const memberRes = await request('/api/v1/member/batch', {
                    method: 'POST',
                    data: { ids: memberIds },
                });
                if (memberRes.success && memberRes.data) {
                    setMembers(memberRes.data);
                }
            }
            
            // 如果有场地ID，获取场地信息
            if (venueIds.length > 0) {
                const venueRes = await request('/api/v1/venue/batch', {
                    method: 'POST',
                    data: { ids: venueIds },
                });
                if (venueRes.success && venueRes.data) {
                    setVenues(venueRes.data);
                }
            }
        } catch (error) {
            console.error('获取关联数据出错:', error);
        }
    };

    // 获取门店列表
    const fetchStoreList = async () => {
        try {
            const res = await fetchStores();
            if (res.success) {
                setStores(res.data.list || []);
            } else {
                message.error(res.message || '获取门店列表失败');
            }
        } catch (error) {
            console.error('获取门店列表出错:', error);
            message.error('获取门店列表失败');
        }
    };

    useEffect(() => {
        fetchOrderList();
        fetchStoreList();
    }, [pagination.current, pagination.pageSize, searchParams]);

    // 查看订单详情
    const handleViewDetail = async (record) => {
        try {
            setLoading(true);
            const res = await fetchOrderDetail(record.id);
            if (res.success) {
                setCurrentOrder(res.data);
                setDetailVisible(true);
            } else {
                message.error(res.message || '获取订单详情失败');
            }
        } catch (error) {
            console.error('获取订单详情出错:', error);
            message.error('获取订单详情失败');
        } finally {
            setLoading(false);
        }
    };

    // 处理状态变更
    const handleStatusChange = (record, status) => {
        setCurrentOrder(record);
        setTargetStatus(status);
        statusForm.resetFields();
        setStatusVisible(true);
    };

    // 提交状态变更
    const handleStatusSubmit = async () => {
        try {
            const values = await statusForm.validateFields();
            setLoading(true);

            const data = {
                id: currentOrder.id,
                status: targetStatus,
                remark: values.remark,
            };

            const res = await updateOrderStatus(data);
            if (res.success) {
                message.success('订单状态更新成功');
                setStatusVisible(false);
                fetchOrderList();
            } else {
                message.error(res.message || '订单状态更新失败');
            }
        } catch (error) {
            console.error('订单状态更新出错:', error);
            message.error('订单状态更新失败');
        } finally {
            setLoading(false);
        }
    };

    // 处理搜索
    const handleSearch = (values) => {
        const params = {};
        if (values.keyword) {
            params.keyword = values.keyword;
        }
        if (values.store_id) {
            params.store_id = values.store_id;
        }
        if (values.venue_id) {
            params.venue_id = values.venue_id;
        }
        if (values.status) {
            params.status = values.status;
        }
        if (values.paymentStatus) {
            params.paymentStatus = values.paymentStatus;
        }
        if (values.dateRange && values.dateRange.length === 2) {
            params.startDate = values.dateRange[0].format('YYYY-MM-DD');
            params.endDate = values.dateRange[1].format('YYYY-MM-DD');
        }

        setSearchParams(params);
        setPagination({
            ...pagination,
            current: 1,
        });
    };

    // 处理重置
    const handleReset = () => {
        form.resetFields();
        setSearchParams({});
        setPagination({
            ...pagination,
            current: 1,
        });
    };

    // 处理表格变化
    const handleTableChange = (pagination, filters, sorter) => {
        setPagination(pagination);
    };

        // 处理换场地
    const handleReschedule = (record) => {
        setCurrentOrder(record);
        fetchVenues(record.store_id).then(res => {
            if (res.success) {
                setVenues(res.data.list || []);
            }
        });
        rescheduleForm.resetFields();
        setRescheduleVisible(true);
    };

    // 提交换场地
    const handleRescheduleSubmit = async () => {
        try {
            const values = await rescheduleForm.validateFields();
            setLoading(true);

            // 检查新场地可用性
            const isAvailable = await checkVenueAvailability(values.new_venue_id, currentOrder.start_time, currentOrder.end_time);
            if (!isAvailable) {
                message.error('新场地在当前时间段内已被占用，请选择其他场地');
                return;
            }

            const data = {
                original_order_id: currentOrder.id,
                new_venue_id: values.new_venue_id,
            };

            const res = await request('/api/v1/order/reschedule', {
                method: 'POST',
                data,
            });

            if (res.success) {
                message.success('换场地成功');
                setRescheduleVisible(false);
                fetchOrderList();
            } else {
                message.error(res.message || '换场地失败');
            }
        } catch (error) {
            console.error('换场地出错:', error);
            message.error('换场地失败');
        } finally {
            setLoading(false);
        }
    };

    // 检查场地可用性
    const checkVenueAvailability = async (venueId, startTime, endTime) => {
        try {
            const res = await request('/api/v1/order/check_availability', {
                method: 'GET',
                params: {
                    venue_id: venueId,
                    start_time: startTime,
                    end_time: endTime,
                },
            });
            return res.success ? res.data.available : false;
        } catch (error) {
            console.error('检查场地可用性出错:', error);
            return false;
        }
    };

    // 处理代客下单
    const handleCreateOrder = async (values) => {
        try {
            setLoading(true);
            const startTime = values.booking_time[0].unix();
            const endTime = values.booking_time[1].unix();
            
            // 先检查场地可用性
            const isAvailable = await checkVenueAvailability(values.venue_id, startTime, endTime);
            if (!isAvailable) {
                message.error('场地在指定时间段内已被占用，请选择其他时间或场地');
                return;
            }

            const params = {
                ...values,
                start_time: startTime,
                end_time: endTime,
            };
            delete params.booking_time;

            const res = await request('/api/v1/order/create_by_admin', {
                method: 'POST',
                data: params,
            });

            if (res.success) {
                message.success('下单成功');
                setCreateOrderVisible(false);
                createOrderForm.resetFields();
                fetchOrderList();
            } else {
                message.error(res.message || '下单失败');
            }
        } catch (error) {
            console.error('下单出错:', error);
            message.error('下单失败');
        } finally {
            setLoading(false);
        }
    };

    // 表格列定义
    const columns = [
        {
            title: '订单号',
            dataIndex: 'order_no',
            key: 'order_no',
            width: 180,
        },
        {
            title: '门店',
            dataIndex: 'store_id',
            key: 'store_id',
            width: 150,
            render: (storeId) => {
                const store = stores.find(s => s.id === storeId);
                return store ? store.name : storeId;
            }
        }, 
        {
            title: '场地',
            dataIndex: 'venue_id',
            key: 'venue_id',
            width: 150,
            render: (venueId) => {
                const venue = venues.find(v => v.id === venueId);
                return venue ? venue.name : venueId;
            }
        },
        {
            title: '会员',
            dataIndex: 'member_id',
            key: 'member_id',
            width: 120,
            render: (userId) => {
                const member = members.find(m => m.id === userId);
                return member ? `${member.name}[${member.phone}]` : userId;
            }
        },
        {
            title: '订单总金额',
            dataIndex: 'total_amount',
            key: 'total_amount',
            width: 120,
            render: (text) => `¥${(text / 100).toFixed(2)}`,
        },
        {
            title: '是否余额支付',
            dataIndex: 'use_balance',
            key: 'use_balance',
            width: 120,
            render: (isBalancePayment) => (isBalancePayment ? <Tag color="success">是</Tag> : <Tag color="default">否</Tag>),
        },
        {
            title: '余额支付金额',
            dataIndex: 'balance_amount',
            key: 'balance_amount',
            width: 120,
            render: (text) => `¥${(text / 100).toFixed(2)}`,
        },
         {
            title: '支付金额',
            dataIndex: 'pay_amount',
            key: 'pay_amount',
            width: 120,
            render: (text) => `¥${(text / 100).toFixed(2)}`,
        },
        {
            title: '订单状态',
            dataIndex: 'status',
            key: 'status',
            width: 100,
            render: (status) => {
                const { text, color } = orderStatusMap[status] || { text: '未知', color: 'default' };
                return <Tag color={color}>{text}</Tag>;
            },
        },
        {
            title: '下单时间',
            dataIndex: 'created_at',
            key: 'created_at',
            width: 180,
            render: (timestamp) => {
                return timestamp ? moment(timestamp * 1000).format('YYYY-MM-DD HH:mm:ss') : '-';
            }
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => {
                const actions = [
                    <Button
                        key="view"
                        type="link"
                        icon={<EyeOutlined />}
                        onClick={() => handleViewDetail(record)}
                    >
                        详情
                    </Button>
                ];

                // 根据订单状态显示不同的操作按钮
                if (record.status === 1) { // 待处理
                    actions.push(
                        <Button
                            key="process"
                            type="link"
                            icon={<CheckOutlined />}
                            style={{ color: '#1890ff' }}
                            onClick={() => handleStatusChange(record, 2)}
                        >
                            处理
                        </Button>
                    );
                }

                if (record.status === 2) { // 处理中
                    actions.push(
                        <Button
                            key="complete"
                            type="link"
                            icon={<CheckOutlined />}
                            style={{ color: '#52c41a' }}
                            onClick={() => handleStatusChange(record, 3)}
                        >
                            完成
                        </Button>
                    );
                }

                // 待处理和处理中的订单可以取消
                if (record.status === 2) { // 已确认的订单可以换场地
                    actions.push(
                        <Button
                            key="reschedule"
                            type="link"
                            icon={<SwapOutlined />}
                            onClick={() => handleReschedule(record)}
                        >
                            换场地
                        </Button>
                    );
                }

                if (record.status === 1 || record.status === 2) {
                    actions.push(
                        <Button
                            key="cancel"
                            type="link"
                            icon={<CloseOutlined />}
                            danger
                            onClick={() => handleStatusChange(record, 4)}
                        >
                            取消
                        </Button>
                    );
                }

                return <Space>{actions}</Space>;
            },
        },
    ];
    return (
        <PageContainer>
            <Card title="订单列表" extra={
                <Space>
                    <Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateOrderVisible(true)}>代客下单</Button>
                    <Button type="primary" icon={<SearchOutlined />} onClick={() => form.submit()}>搜索</Button>
                    <Button icon={<ReloadOutlined />} onClick={handleReset}>重置</Button>
                </Space>
            }>
                <Form form={form} layout="inline" onFinish={handleSearch}>
                    <Form.Item name="keyword" label="关键字">
                        <Input placeholder="订单号、会员名" />
                    </Form.Item>
                    <Form.Item name="store_id" label="门店">
                        <Select placeholder="请选择门店" allowClear>
                            {stores.map((store) => (
                                <Option key={store.id} value={store.id}>
                                    {store.name}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="venue_id" label="场地">
                        <Select placeholder="请选择场地" allowClear>
                            {venues.map((venue) => (
                                <Option key={venue.id} value={venue.id}>
                                    {venue.name}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="status" label="订单状态">
                        <Select placeholder="请选择订单状态">
                            <Option value={1}>待处理</Option>
                            <Option value={2}>处理中</Option>
                            <Option value={3}>已完成</Option>
                            <Option value={4}>已取消</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item name="payment_status" label="支付状态">
                        <Select placeholder="请选择支付状态">
                            <Option value={1}>未支付</Option>
                            <Option value={2}>已支付</Option>
                            <Option value={3}>已退款</Option>
                        </Select>
                    </Form.Item>
                </Form>
                <Table
                    columns={columns}
                    dataSource={orders}
                    rowKey="id"
                    loading={loading}
                    pagination={pagination}
                    onChange={handleTableChange}
                />
            </Card>

            <Modal
                title="订单详情"
                visible={detailVisible}
                onCancel={() => setDetailVisible(false)}
                footer={null}
                width={1000}
            >
                {currentOrder && (
                    <Descriptions title="订单详情" bordered>
                        <Descriptions.Item label="订单号">{currentOrder.order_no}</Descriptions.Item>
                        <Descriptions.Item label="门店">
                            {stores.find(s => s.id === currentOrder.store_id)?.name || currentOrder.store_id}
                        </Descriptions.Item>
                        <Descriptions.Item label="会员">
                            {members.find(m => m.id === currentOrder.member_id)?.name || currentOrder.member_id}
                        </Descriptions.Item>
                        <Descriptions.Item label="场地">
                            {venues.find(v => v.id === currentOrder.venue_id)?.name || currentOrder.venue_id}
                        </Descriptions.Item>
                        <Descriptions.Item label="订单金额">
                            <span style={{ color: 'green' }}>¥{(currentOrder.total_amount / 100).toFixed(2)}</span>
                        </Descriptions.Item>
                        <Descriptions.Item label="订单状态">
                            {(() => {
                                const { text, color } = orderStatusMap[currentOrder.status] ||
                                    { text: '未知', color: 'default' };
                                return <Tag color={color}>{text}</Tag>;
                            })()}
                        </Descriptions.Item>
                        <Descriptions.Item label="下单时间">
                            {currentOrder.created_at ? moment(currentOrder.created_at * 1000).format('YYYY-MM-DD HH:mm:ss') : '-'}
                        </Descriptions.Item>
                        <Descriptions.Item label="开始时间">
                            {currentOrder.start_time ? moment(currentOrder.start_time * 1000).format('YYYY-MM-DD HH:mm:ss') : '-'}
                        </Descriptions.Item>
                        <Descriptions.Item label="结束时间">
                            {currentOrder.end_time ? moment(currentOrder.end_time * 1000).format('YYYY-MM-DD HH:mm:ss') : '-'}
                        </Descriptions.Item>
                        <Descriptions.Item label="备注">{currentOrder.remark || '-'}</Descriptions.Item>
                    </Descriptions>
                )}
            </Modal>

            <Modal
                title="换场地"
                visible={rescheduleVisible}
                onCancel={() => setRescheduleVisible(false)}
                onOk={handleRescheduleSubmit}
                confirmLoading={loading}
            >
                <Form form={rescheduleForm} layout="vertical">
                    <Form.Item
                        name="new_venue_id"
                        label="新场地"
                        rules={[{ required: true, message: '请选择新场地' }]}
                    >
                        <Select placeholder="请选择新场地" allowClear>
                            {venues.map((venue) => (
                                <Option key={venue.id} value={venue.id}>
                                    {venue.name}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                </Form>
            </Modal>

            <Modal
                title="订单状态变更"
                visible={statusVisible}
                onCancel={() => setStatusVisible(false)}
                footer={null}
                width={600}
            >
                <Form form={statusForm} layout="vertical" onFinish={handleStatusSubmit}>
                    <Form.Item name="remark" label="备注">
                        <Input.TextArea placeholder="请输入备注信息" />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" loading={loading}>
                            确认{
                                targetStatus === 2 ? '处理' : 
                                targetStatus === 3 ? '完成' : '取消'
                            }
                        </Button>
                        <Button style={{ marginLeft: 8 }} onClick={() => setStatusVisible(false)}>
                            取消
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>

            <Row gutter={24} style={{ marginBottom: 24 }}>
                <Col span={6}>
                    <Card>
                        <Statistic
                            title="总订单数"
                            value={statistics.total_orders}
                            prefix={<ShoppingCartOutlined />}
                            loading={loading}
                        />
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <Statistic
                            title="待处理订单"
                            value={statistics.pending_orders}
                            valueStyle={{ color: '#faad14' }}
                            prefix={<ClockCircleOutlined />}
                            loading={loading}
                        />
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <Statistic
                            title="今日订单"
                            value={statistics.today_orders}
                            valueStyle={{ color: '#1890ff' }}
                            prefix={<CalendarOutlined />}
                            loading={loading}
                        />
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <Statistic
                            title="总金额"
                            value={(statistics.total_amount / 100).toFixed(2)}
                            valueStyle={{ color: '#52c41a' }}
                            prefix="¥"
                            loading={loading}
                        />
                    </Card>
                </Col>
            </Row>
                    <Modal
                title="代客下单"
                visible={createOrderVisible}
                onCancel={() => setCreateOrderVisible(false)}
                onOk={() => createOrderForm.submit()}
                confirmLoading={loading}
            >
                <Form form={createOrderForm} layout="vertical" onFinish={handleCreateOrder}>
                    <Form.Item name="store_id" label="门店" rules={[{ required: true }]}>
                        <Select placeholder="请选择门店" allowClear>
                            {stores.map((store) => (
                                <Option key={store.id} value={store.id}>
                                    {store.name}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="venue_id" label="场地" rules={[{ required: true }]}>
                        <Select placeholder="请选择场地" allowClear>
                            {venues.map((venue) => (
                                <Option key={venue.id} value={venue.id}>
                                    {venue.name}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="member_id" label="会员" rules={[{ required: true }]}>
                         <Select
                            showSearch
                            placeholder="搜索并选择会员"
                            optionFilterProp="children"
                            filterOption={(input, option) =>
                                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {members.map((member) => (
                                <Option key={member.id} value={member.id}>
                                    {`${member.name}[${member.phone}]`}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="booking_time" label="预定时间" rules={[{ required: true }]}>
                        <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" />
                    </Form.Item>
                     <Form.Item name="remark" label="备注">
                        <Input.TextArea placeholder="请输入备注信息" />
                    </Form.Item>
                </Form>
            </Modal>
        </PageContainer>
    );
};
export default OrderList;